package com.htgd.gardenexpo.config;

import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class DecryptingRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] cachedBody;

    public DecryptingRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.cachedBody = readInputStream(request.getInputStream()); // 原始请求体
    }

    // 新构造函数，接受解密后的内容
    public DecryptingRequestWrapper(HttpServletRequest request, String decryptedBody) throws IOException {
        super(request);
        this.cachedBody = decryptedBody.getBytes(StandardCharsets.UTF_8); // 将解密后的字符串转换为字节数组
    }

    private byte[] readInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;

        while ((length = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, length);
        }

        return baos.toByteArray();
    }

    @Override
    public ServletInputStream getInputStream() {
        return new ServletInputStream() {
            private final ByteArrayInputStream bais = new ByteArrayInputStream(cachedBody);

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return bais.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // No-op
            }
        };
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream(), StandardCharsets.UTF_8));
    }

    public String getCachedBody() {
        return new String(cachedBody, StandardCharsets.UTF_8);
    }
}
